<template>
  <div class="payment-password-page">
    <el-card class="balance-card">
      <div class="balance-header">
        <div class="balance-info">
          <h3>账户余额: {{ user.userInfo.money }} 元</h3>
        </div>
        <div>
          <el-button type="success" @click="onRechargeClick">充值余额</el-button>
          <el-button type="warning" @click="onResetBalanceClick">重置余额</el-button>
          <el-button type="primary" @click="onChangePasswordClick">修改支付密码</el-button>
        </div>
      </div>
    </el-card>

    <!-- 充值余额的对话框 -->
    <el-dialog title="充值余额" v-model="rechargeDialogVisible" width="400px">
      <el-form
          :model="rechargeForm"
          :rules="rechargeRules"
          ref="rechargeFormRef"
          label-width="120px"
      >
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="rechargeForm.amount" placeholder="请输入充值金额" type="number"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmitRecharge">提交充值</el-button>
          <el-button @click="onResetRecharge">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改支付密码的对话框 -->
    <el-dialog title="修改支付密码" v-model="dialogVisible" width="400px">
      <el-form
          v-if="!isVerified"
          :model="verifyForm"
          :rules="verifyRules"
          ref="verifyFormRef"
          label-width="120px"
          class="verify-form"
      >
        <el-form-item label="当前支付密码" prop="currentPaymentPassword">
          <el-input
              type="password"
              v-model="verifyForm.currentPaymentPassword"
              placeholder="请输入当前支付密码"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onVerifyPassword">验证密码</el-button>
        </el-form-item>
      </el-form>

      <!-- 修改支付密码表单 -->
      <el-form
          v-if="isVerified"
          :model="changeForm"
          :rules="changeRules"
          ref="changeFormRef"
          label-width="120px"
          class="change-form"
      >
        <el-form-item label="新支付密码" prop="newPaymentPassword">
          <el-input
              type="password"
              v-model="changeForm.newPaymentPassword"
              placeholder="请输入新支付密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="确认新支付密码" prop="confirmPaymentPassword">
          <el-input
              type="password"
              v-model="changeForm.confirmPaymentPassword"
              placeholder="请确认新支付密码"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmitChange">提交修改</el-button>
          <el-button @click="onResetChange">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import userApi from "@/api/UserApi.js";
import { userStore } from "@/stores/user.js";

// 控制对话框显示
const dialogVisible = ref(false);
const rechargeDialogVisible = ref(false); // 控制充值对话框显示

// 是否验证成功
const isVerified = ref(false);

// 表单数据
const verifyForm = ref({
  currentPaymentPassword: '',
});
const changeForm = ref({
  newPaymentPassword: '',
  confirmPaymentPassword: '',
});
const rechargeForm = ref({ amount: '' }); // 充值表单

// 用户信息
const user = userStore();

// 验证表单规则
const verifyFormRef = ref(null);
const changeFormRef = ref(null);
const rechargeFormRef = ref(null); // 充值表单引用

const verifyRules = {
  currentPaymentPassword: [
    { required: true, message: '请输入当前支付密码', trigger: 'blur' },
    { min: 6, message: '支付密码至少6位', trigger: 'blur' },
  ],
};

const changeRules = {
  newPaymentPassword: [
    { required: true, message: '请输入新支付密码', trigger: 'blur' },
    { min: 6, message: '支付密码至少6位', trigger: 'blur' },
  ],
  confirmPaymentPassword: [
    { required: true, message: '请确认新支付密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== changeForm.value.newPaymentPassword) {
          callback(new Error('两次输入的支付密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { min: 1, message: '充值金额最少为1元', trigger: 'blur' },
  ],
};

// 获取账户余额
const fetchBalance = async () => {
  const resp = await userApi.getInfo();
  if (resp.code === 10000) {
    user.updateUser(resp.data);
  }
};

// 充值余额
const onRechargeClick = () => {
  rechargeDialogVisible.value = true;
};

const onSubmitRecharge = () => {
  rechargeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userApi.rechargeBalance(rechargeForm.value.amount); // 调用API进行余额充值
        if (response.code === 10000) {
          ElMessage.success('充值成功');
          rechargeDialogVisible.value = false;
          fetchBalance(); // 充值后更新余额
        } else {
          ElMessage.error(response.msg || '充值失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后再试');
      }
    }
  });
};

// 重置充值表单
const onResetRecharge = () => {
  rechargeFormRef.value.resetFields();
};

// 重置余额
const onResetBalanceClick = async () => {
  const response = await userApi.getInfo(); // 调用userApi重置余额
  if (response.code === 10000) {
    user.updateUser(response.data);
    ElMessage.success('余额已重置');
  } else {
    ElMessage.error(response.msg || '重置余额失败');
  }
};

// 打开修改支付密码对话框
const onChangePasswordClick = () => {
  userApi.verifyPayPassword(null).then((resp) => {
    if (resp.code === 10000) {
      // 没有设置密码
      dialogVisible.value = true;
      isVerified.value = true;
    } else {
      // 有设置支付密码
      dialogVisible.value = true;
    }
  });
};

// 验证支付密码
const onVerifyPassword = () => {
  verifyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userApi.verifyPayPassword(verifyForm.value.currentPaymentPassword);
        if (response.code === 10000) {
          ElMessage.success('支付密码验证成功');
          isVerified.value = true; // 验证通过
        } else {
          ElMessage.error(response.msg || '支付密码验证失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后再试');
      }
    }
  });
};

// 修改支付密码
const onSubmitChange = () => {
  changeFormRef.value.validate(async (valid) => {
    if (valid) {
      const response = await userApi.changePayPassword(
          verifyForm.value.currentPaymentPassword,
          changeForm.value.newPaymentPassword,
          changeForm.value.confirmPaymentPassword
      ); // 调用userApi修改支付密码
      if (response.code === 10000) {
        ElMessage.success('支付密码修改成功');
        dialogVisible.value = false;
        isVerified.value = false;
        onResetChange();
      } else {
        ElMessage.error(response.msg || '修改支付密码失败');
      }
    }
  });
};

// 重置修改表单
const onResetChange = () => {
  changeFormRef.value.resetFields();
};

// 初始化获取余额
onMounted(() => {
  fetchBalance();
});
</script>

<style scoped>
.payment-password-page {
  padding: 20px;
  background-color: #f0f2f5;
}

.balance-card {
  max-width: 600px;
  margin: 0 auto;
  min-height: 200px;
}

.balance-header {
  text-align: center;
  align-items: center;
}

.balance-info {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>
